package com.itheima.controller;

import com.itheima.common.constant.MessageConstant;
import com.itheima.common.entity.Result;
import com.itheima.pojo.Member;
import com.itheima.service.MemberService;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.data.redis.core.StringRedisTemplate;
import org.springframework.web.bind.annotation.*;

import java.time.LocalDateTime;
import java.util.Date;
import java.util.Map;

@RestController
@Slf4j
@RequestMapping("/member")
public class MemberConroller {

    @Autowired
    private StringRedisTemplate redisTemplate;

    @Autowired
    private MemberService memberService;

    @PostMapping("/login")
    public Result login(@RequestBody Map map){
        String telephone = (String) map.get("telephone");//获取手机号
        String code = (String) map.get("validateCode");
        Object rediscode = redisTemplate.opsForValue().get(telephone + "logincode");//获取验证码
         if(rediscode!=null && code!=null && code.equals(rediscode)){
            //判断是否为会员
            Member member = memberService.findByTelephone(telephone);
            if ( member == null){
                //不是会员，自动注册
                member = new Member();
                member.setRegTime(new Date());
                member.setPhoneNumber(telephone);
                memberService.add(member);
            }
            return new Result(true, MessageConstant.LOGIN_SUCCESS);
        }
        return new Result(false, MessageConstant.VALIDATECODE_ERROR);
    }
}
